package cn.hist.hfp.controller;

import cn.hist.hfp.RoleType;
import cn.hist.hfp.entity.Species;
import cn.hist.hfp.service.SpeciesService;
import cn.hist.hfp.util.Authentication;
import cn.hist.hfp.util.MyResponse;
import cn.hist.hfp.vo.SpeciesVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/species")
public class SpeciesController {

    private final
    SpeciesService speciesService;

    private final
    Authentication authentication;

    @Autowired
    public SpeciesController(SpeciesService speciesService, Authentication authentication) {
        this.speciesService = speciesService;
        this.authentication = authentication;
    }

    @PostMapping
    public ResponseEntity<SpeciesVO> create(@RequestBody Species species, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.MANAGER);
        return new MyResponse<SpeciesVO>().response(201, token, speciesService.create(species));
    }

    @GetMapping("/{id}")
    public SpeciesVO findOne(@PathVariable int id) {
        return speciesService.findOne(id);
    }

    @GetMapping
    public List<SpeciesVO> findAll() {
        return speciesService.findAll();
    }

    @PutMapping
    public ResponseEntity<SpeciesVO> update(@RequestBody Species species, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.MANAGER);
        return new MyResponse<SpeciesVO>().response(200, token, speciesService.update(species));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Integer> delete(@PathVariable int id, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.MANAGER);
        return new MyResponse<Integer>().response(200, authentication.refreshToken(token), speciesService.delete(id));
    }
}
